package global

import (
	"beergo/lib/base/controller"
	"beergo/lib/tool"
	twig "beergo/plugins/twig/lib/go"
	"github.com/beego/beego/v2/server/web"
	"reflect"
)

type Controller struct {
	controller.BaseController
}

func init() {
	web.Router("/_config",&Controller{},"*:GetConfigAction")
	web.Router("/_conf_v",&Controller{},"*:GetConfigViewAction")
	web.Router("/_conf_form",&Controller{},"*:FormAction")
	web.Router("/_config_tables",&Controller{},"*:GetTableChoiceAction")
	web.Router("/_config_fields",&Controller{},"*:GetFilesAction")
}

func (this Controller) GetTableChoiceAction (){
	config:= ModelJsonConfig.Get()
	type Item struct{
		Key string `json:"key"`
		Value string `json:"value"`
	}
	list := make([]Item,0)
	for _, m := range config {
		table,ok:=m["table"].(map[string]interface {})
		if ok {
			list = append(list, Item{table["name"].(string),table["name"].(string)})
		}else {
			println(reflect.TypeOf(m["table"]).String())
		}
	}
	this.JsonData["lists"] = list
	this.ReturnSuccess("OK",this.JsonData)
}
func (this Controller) GetFilesAction (){
	tableName:=this.GetParamString("table")
	config:= ModelJsonConfig.Get()
	type Item struct{
		Key string `json:"key"`
		Value string `json:"value"`
	}
	list := make([]Item,0)
	for _, m := range config {
		table,ok:=m["table"].(map[string]interface {})
		if ok {
			if tableName == table["name"].(string) {
				this.JsonData["lists"] = table["fields"]
				this.ReturnSuccess("OK",this.JsonData)
			}
			list = append(list, Item{table["name"].(string),table["name"].(string)})
		}else {
			println(reflect.TypeOf(m["table"]).String())
		}
	}
	this.JsonData["lists"] = make([]interface{},0)
	this.ReturnSuccess("OK",this.JsonData)
}
func (this Controller) GetConfigAction (){
	//data:=ModelJsonConfig.Get()
	this.ReturnSuccess("OK",ModelJsonConfig.Get())
}

func (this Controller) GetConfigViewAction (){
	println("here")
	html:=twig.Render("/dbconfig/db.twig",tool.M{
		"conf":ModelJsonConfig.Get(),
	})
	//tool.JsonLog(html)
	this.Html(html)
}

func (this Controller) FormAction (){
	html:=twig.Render("/diy/form.twig",tool.M{
		"conf":ModelJsonConfig.Get(),
	})
	this.Html(html)
}
